import { getToken } from '@/utils'
import './index.scss'
import { Button, Card, Tabs, List, Row, Col, Space, Dropdown, message, Popconfirm } from 'antd'
// import { Sticky } from 'react-sticky'
import React, { useEffect, useLayoutEffect, useState, useRef, useCallback } from 'react'
import { http, baseUrlWs } from '@/utils'
import { useStore } from '@/store'
import Tmptransfer from './components/Tmptransfer'
import OrderModalopen from './components/Ordermodalopen'
import { ArrowUpOutlined, ArrowDownOutlined } from '@ant-design/icons'
import CheckKlineOpen from './components/CheckKlineOpen'

const Signal = () => {
    /**
     * WebSocket
     */
    const ws = useRef(WebSocket | null) // WebSocket 对象
    const readyState = useRef()
    const tabsDataRef = useRef()
    const tabsIndexRef = useRef()
    const { loginStore } = useStore()
    const [tabsIndex, setTabsIndex] = useState('')
    const [tabsData, setTabsData] = useState([])
    const [tabsDataSort, setTabsDataSort] = useState([])
    const [loadSort, setLoadSort] = useState(true)
    const [unTabsData, setUnTabsData] = useState([])
    const [delBtnDis, setDelBtnDis] = useState(true)

    // 配置品种预警组
    let ChildRef = React.createRef()
    const showModalOpen = (item) => {
        ChildRef.current.openConfigModalOpen(item)
    }
    const changeConfigModal = (msg) => {
        console.log('子组件调用：' + msg)
    }
    let OrderRef = React.createRef()
    const showOrderModalOpen = (item) => {
        OrderRef.current.openConfigModalOpen(item)
    }
    let timer2 = useRef()
    let KlineRef = React.createRef()
    const showKlineModalOpen = (item) => {
        console.log(111, item)
        KlineRef.current.openConfigModalOpen(item)
    }

    // 快速添加删除
    const configVariety = async (type, row, tabsRow) => {
        const data = {
            setType: type,
            featureCode: row.featureCode
        }
        // 删除
        if (type === 0) {
            const list = tabsData.filter(item => item.key === tabsIndex)
            data.alarmGroupId = list[0].id
            data.alarmGroupText = list[0].groupAlarmName
        }
        // 添加
        if (type === 1) {
            data.alarmGroupId = tabsRow.id
            data.alarmGroupText = tabsRow.groupAlarmName
        }
        console.log(data)
        const res = await http.post('/alarm/deliversign/quickAddAlarmGroupIntoFeature', data)
        message.success(res.body)
    }

    const webSocketInit = useCallback(() => {
        const stateArr = [
            '正在链接中...',
            '已经链接并且可以通讯',
            '连接正在关闭',
            '连接失败，请尝试重新连接',
        ]
        let heartbeat = 0
        timer2.current = setInterval(() => {
            if (heartbeat >= 5 && ws.current.readyState !== 1) {
                heartbeat = 0
                clearTimeout(timer2.current)
                webSocketInit()
            }
            heartbeat += 1
        }, 1000)
        let timer = null
        if (!ws.current || ws.current.readyState === 3) {
            // ws.current = new WebSocket(`ws://192.168.12.105:7070?token=${getToken()}`)  // 本地测试
            ws.current = new WebSocket(`${baseUrlWs}alarm/webSocket?token=${getToken()}`)
            ws.current.onopen = _e => {
                readyState.current = stateArr[ws.current?.readyState ?? 0]
                return console.log('success', 'socket连接成功')
            }
            ws.current.onclose = _e => {
                readyState.current = stateArr[ws.current?.readyState ?? 0]
                return console.log('close', _e)
            }
            ws.current.onerror = e => {
                readyState.current = stateArr[ws.current?.readyState ?? 0]
                return console.log('error', e)
            }
            ws.current.onmessage = e => {
                heartbeat = 0
                const body = JSON.parse(e.data)
                if (!tabsDataRef.current) return
                let upData = tabsDataRef.current.map(item => {
                    // 未读信息数量 当前预警分组下的预警信息  且userIds必须包含当前用户
                    const badge = tabsIndexRef.current === item.key ? 0 : item.badge + body.filter(citem => {
                        return citem.groupId === item.id && citem.userIds.indexOf(+loginStore.userId) !== -1
                    }).length
                    // 筛选当前预警分组下的预警信息 且userIds必须包含当前用户
                    let listData = body.filter(citem => {
                        return citem.groupId === item.id && citem.userIds.indexOf(+loginStore.userId) !== -1
                    })
                    // 新增预警信息添加呼吸灯时间戳
                    listData = listData.map(childitem => {
                        return {
                            ...childitem,
                            direction: childitem.factorName.indexOf('⬇') !== -1 ? 1 : 0,
                            factorName: childitem.factorName.replace(/⬇|⬆/g, ""),
                            time: new Date().getTime(),
                        }
                    })
                    let row = {
                        ...item,
                        listData: [...listData, ...item.listData.splice(0, 100)],
                        badge: badge
                    }
                    return row
                })
                tabsDataRef.current = [...upData]
                setTabsData([...upData])
                /**
                 * webscoke 心跳机制
                 * 1. 超时3s清空呼吸灯
                 * 2. 短线重连 (路由跳转不重连)
                 */
                clearTimeout(timer)
                timer = setTimeout(() => {
                    upData = upData.map(item => {
                        item = {
                            ...item,
                            listData: item.listData.map(citem => {
                                citem = {
                                    ...citem,
                                    time: new Date().getTime() - 3000,
                                }
                                return citem
                            }),
                        }
                        return item
                    })
                    tabsDataRef.current = [...upData]
                    setTabsData([...upData])
                }, 3000)
            }
        } else {
            heartbeat = 0
            console.log('浏览器不支持WebSocket')
        }
    }, [ws, loginStore])


    useEffect(() => {
        const getTabs = async () => {
            const res = await http.post('/alarm/deliversign/getAlarmGroupByUserId', { userId: loginStore.userId })
            const list = res.body.map(item => {
                const row = {
                    ...item,
                    listData: [],
                    key: `_${item.id}`,
                    badge: 0
                }
                return row
            })
            const listSort = list.filter(item => item.createdBy === +loginStore.userId)
            setTabsDataSort(listSort)
            console.log('预警组列表', list)
            if (list.length) {
                setTabsIndex(`_${list[0].id}`)
                tabsIndexRef.current = `_${list[0].id}`
                getHistorical(list)
            }

        }
        const getHistorical = ((list) => {
            http.post('/alarm/deliversign/findTbUserAlarmInfosByUserId', {
                userId: loginStore.userId,
                groupId: list[0].id,
                pageNum: 1,
                pageSize: 100
            }).then((res) => {
                const listData = res.body.list.map(item => {
                    return {
                        ...item,
                        direction: item.factorName.indexOf('⬇') !== -1 ? 1 : 0,
                        factorName: item.factorName.replace(/⬇|⬆/g, ""),
                    }
                })
                list[0].listData = listData
                const tabsData = [...list]
                console.log(list[0].groupAlarmName + '历史记录', [...listData])
                tabsDataRef.current = [...tabsData]
                setTabsData(tabsDataRef.current)
            })
        })
        if (loadSort) {
            getTabs()
        }
    }, [loginStore, loadSort])


    /** 
    * 初始化 WebSocket
    * 且使用 WebSocket 原生方法获取信息
    *  
    **/
    useLayoutEffect(() => {
        webSocketInit()
        return () => {
            ws.current?.close()
            clearTimeout(timer2.current)
        }
    }, [ws, webSocketInit])

    const tabsChange = (e) => {
        setTabsIndex(e)
        tabsIndexRef.current = e
        console.log(tabsDataRef.current)
        const row = tabsDataRef.current.filter(item => item.key === e)[0]
        row.badge = 0
        getHistorical(tabsDataRef.current)
        // setTabsData(tabsDataRef.current)

    }
    const getHistorical = ((list) => {
        const row = list.filter(item => item.key === tabsIndexRef.current)[0]
        http.post('/alarm/deliversign/findTbUserAlarmInfosByUserId', {
            userId: loginStore.userId,
            groupId: row.id,
            pageNum: 1,
            pageSize: 100
        }).then((res) => {
            const listData = res.body.list.map(item => {
                return {
                    ...item,
                    direction: item.factorName.indexOf('⬇') !== -1 ? 1 : 0,
                    factorName: item.factorName.replace(/⬇|⬆/g, ""),
                }
            })
            row.listData = listData
            tabsDataRef.current = [...list]
            console.log(row.groupAlarmName + '历史记录', [...listData])
            setTabsData(tabsDataRef.current)
        })
    })
    // 获取可编辑预警组
    const getDropList = async (e, row) => {
        const res = await http.post('/alarm/deliversign/getSelectedAndUnSelectedAlarmGroupByFeatureId', {
            userId: loginStore.userId,
            featureId: row.featureId,
            groupAlarmName: ""
        })
        const list = tabsData.filter(item => item.key === tabsIndex)[0]
        let btnDis = true
        const myGroupList = res.body.selectedAlarmGroupByFeatureId ? res.body.selectedAlarmGroupByFeatureId.filter(item => {
            return +item.createdBy === +loginStore.userId
        }) : []
        if (myGroupList) {
            for (let index = 0; index < myGroupList.length; index++) {
                const element = myGroupList[index]
                if (element.id === list.id) {
                    btnDis = false
                }
            }
        }
        setDelBtnDis(btnDis)
        console.log(res)
        setUnTabsData(res.body.unSelectedAlarmGroupByFeatureId)
    }
    // 排序
    const sortTabsData = (sort, row) => {
        let index = null
        const list = [...tabsDataSort].filter((item, i) => {
            if (item.id === row.id) {
                index = i
            }
            return item.id !== row.id
        })
        if (sort === 'des') {
            list.splice(index + 1, 0, row)
        } else {
            list.splice(index - 1, 0, row)
        }
        setTabsDataSort(list)
    }
    const sortSubmit = () => {
        setLoadSort(false)
        const sortList = [
            ...tabsData.filter(item => item.createdBy !== +loginStore.userId),
            ...tabsDataSort
        ]
        http.post('/alarm/deliversign/saveOrderByInfoByUserId', {
            userId: loginStore.userId,
            orderByInfos: sortList.map(item => item.id)
        }).then(res => {
            setLoadSort(true)
            message.success(res.body)
        })
    }
    return (
        <>
            <Card title="预警信号">
                <Tabs
                    activeKey={tabsIndex}
                    onChange={tabsChange}
                    type="card"
                    renderTabBar={(props, DefaultTabBar) => (<>
                        <div className='signal-sort'>
                            <Popconfirm
                                icon={false}
                                showCancel={false}
                                onConfirm={sortSubmit}
                                title={<>
                                    <div className='sortContent'>
                                        {
                                            tabsDataSort.map((item, i) => (<Row
                                                key={item.id}
                                                style={{ borderBottom: '1px solid #f0f0f0', padding: '5px 0' }}
                                            >
                                                <Col span={2}>{++i}.</Col>
                                                <Col span={16}>{item.groupAlarmName}</Col>
                                                <Col span={6}>
                                                    <Button
                                                        disabled={i === tabsDataSort.length}
                                                        type='link'
                                                        size="small"
                                                        onClick={() => sortTabsData('des', item)}
                                                        icon={<ArrowDownOutlined />}
                                                    ></Button>
                                                    <Button
                                                        disabled={i === 1}
                                                        type='link'
                                                        size="small"
                                                        icon={<ArrowUpOutlined />}
                                                        onClick={() => sortTabsData('asc', item)}
                                                    ></Button>
                                                </Col>
                                            </Row>))
                                        }
                                    </div>
                                </>}
                            >
                                <Button size="small" onClick={() => { }} >排序


                                </Button>
                            </Popconfirm>
                        </div>
                        <DefaultTabBar
                            {...props}
                            className='signal-tab-bar'
                        />
                    </>
                    )}
                    items={tabsData.map(item => {
                        return {
                            label: item.badge > 0 ? <div style={{ position: 'relative' }}>
                                <span style={{ paddingRight: '15px' }}> {item.groupAlarmName}</span>
                                <span className='panelBadge'>{item.badge > 99 ? '+99' : item.badge}</span>
                            </div> : <div>
                                <span>{item.groupAlarmName}</span>
                            </div>,
                            key: item.key,
                            children: (
                                <>
                                    <List
                                        bordered
                                        size='small'
                                        header={
                                            <Row>
                                                <Col span={8}>品种名称</Col>
                                                <Col span={4}>预警时间</Col>
                                                <Col span={2}>预警周期</Col>
                                                <Col span={2}>总分</Col>
                                                <Col span={4}>预警因子</Col>
                                                <Col span={4}>操作</Col>
                                            </Row>
                                        }
                                        dataSource={item.listData}
                                        renderItem={(citem, index) => {
                                            return <List.Item
                                                key={citem.featureName}
                                                style={{ border: 0 }} className={{ "fade-in": (citem.time + 3000) >= new Date().getTime(), "fade": true, "hoverBlue": true }}
                                            >
                                                <Row style={{ width: '100%', }}>
                                                    <Col span={8}>
                                                        <Space>
                                                            <div>{citem.featureName}</div>
                                                            <div>{citem.featureCode}</div>
                                                            <div className='trading'>{citem.marginTrading ? '融' : ''}</div>
                                                        </Space>
                                                    </Col>
                                                    <Col span={4}>{citem.datetime || citem.dateTime}</Col>
                                                    <Col span={2}>{citem.freqName}</Col>
                                                    <Col span={2}>{citem.score}</Col>
                                                    <Col span={4}>
                                                        {citem.factorName}
                                                        {citem.direction ? <svg className="icon" aria-hidden="true" style={{ color: '#00E600' }}>
                                                            <use xlinkHref="#icon-paixu"></use>
                                                        </svg> : <svg className="icon" aria-hidden="true" style={{ color: '#FF3232' }}>
                                                            <use xlinkHref="#icon-xiangshang"></use>
                                                        </svg>}
                                                    </Col>
                                                    <Col span={4}>
                                                        <Button size="small" onClick={() => showOrderModalOpen(citem)} style={{ marginRight: 15 }}>下单</Button>
                                                        <Dropdown
                                                            onOpenChange={(e) => getDropList(e, citem)}
                                                            menu={{
                                                                items: [
                                                                    { label: '删除', key: '1', disabled: delBtnDis, onClick: (e) => configVariety(0, citem) },
                                                                    {
                                                                        label: '添加到', key: '2', children: unTabsData.map(titem => {
                                                                            return {
                                                                                label: titem.groupAlarmName,
                                                                                key: titem.id,
                                                                                onClick: (e) => configVariety(1, citem, titem)
                                                                            }
                                                                        })
                                                                    }
                                                                ],
                                                            }}
                                                            trigger={['contextMenu']}
                                                        >
                                                            <Button size="small" onClick={() => showModalOpen(citem)} style={{ marginRight: 15 }}>配置预警组</Button>
                                                        </Dropdown>
                                                        <Button size="small" onClick={() => showKlineModalOpen(citem)}>查看K线</Button>
                                                    </Col>
                                                </Row>
                                            </List.Item>
                                        }}
                                    />
                                </>
                            )
                        }
                    })}
                />
            </Card>
            <Tmptransfer tabsData={tabsData} onRef={ChildRef} changeConfigModal={changeConfigModal} />
            <OrderModalopen tabsData={tabsData} onRef={OrderRef} changeConfigModal={changeConfigModal} />
            <CheckKlineOpen tabsData={tabsData} onRef={KlineRef} changeConfigModal={changeConfigModal} />
        </>
    )
}
export default Signal